package com.keter.framework.web.component.sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;

/**
 * Created by shadowedge on 2019/5/11.
 */
@Component("SIDHolder")
public class SIDHolder {

    public final static String KEY_SID = "x-sid";

    @Autowired
    private Sequencer sequencer;

    private static ThreadLocal<Long> sid = new ThreadLocal<>();

    public Long generate() {
        sid.set(sequencer.genId());
        return get();
    }

    public void setSid(Long id) {
        sid.set(id);
    }

    public Long get() {
        return sid.get();
    }

    public Long getOrGenerate() {
        return sid.get()==null?generate():sid.get();
    }


    /**
     * 生成带sid的消息头
     * @param sid
     * @return
     */
    public static HttpHeaders addSidToHeaders(HttpHeaders headers, Long sid){
        headers.add(SIDHolder.KEY_SID, String.valueOf(sid));
        return headers;
    }

}
